# coding=utf-8
__author__ = 'liubin'

from sqlalchemy.orm import joinedload
from tornado import gen
import jsonpickle
from tornado_json.requesthandlers import APIHandler
from project.tools import HandlerMixin
from project.models import User, MenuRole
from tornado.web import asynchronous
from tornado.concurrent import run_on_executor
from tornado.gen import coroutine
from project.tools import md5, unblock, to_json


class IdentityHandler(HandlerMixin, APIHandler):
    """
    获得用户信息
    """
    #@asynchronous
    #@coroutine
    @unblock
    def get(self):
        """
        GET方法
        """
        result = {}
        user_id = self.get_secure_cookie('user')
        #user_id = 'admin'
        if user_id:
            #user =  self.call_blocking(user_id)
            #user = self.call_blocking(user_id)
            user = self.db_conn.query(User).options(joinedload(User.role, innerjoin=True))\
             .filter(User.userId == user_id).first()
            if user:
                print(type(user.role.menus))
                menus = [menu for menu in user.role.menus if menu.enabled == True]
                menuRoles = self.db_conn.query(MenuRole).all()
                print(menus)
                result = {
                    'userId': user.userId,
                    'name': user.name,
                    'roles': ['ANONYMOUS', user.role.code],
                    'menus': menus,
                    'menuRoles': menuRoles
                    #'xsrf_token': self.xsrf_token
                }
                print(result)
                self.success(to_json(result))
            else:
                self.fail(u'未登录')
        else:
            self.fail(u'未登录')
        #user = self.call_blocking(user_id)
        #self.success(jsonpickle.encode(user, unpicklable=False))

    #@run_on_executor
    # def call_blocking(self, user_id):
    #     #session_base = scoped_session(session_factory)
    #     #session = session_base()
    #
    #     user = self.db_conn.query(User).options(joinedload(User.role, innerjoin=True))\
    #         .filter(User.userId == user_id).first()
    #
    #     #session_base.remove()
    #     return user


class LoginHandler(HandlerMixin, APIHandler):
    """
    登录
    """
    @asynchronous
    @coroutine
    def post(self):
        """
        POST方法
        :return:
        """
        result = yield self.call_blocking()
        if result['success']:
            self.success(jsonpickle.encode(result['data'], unpicklable=False))
        else:
            self.fail(result['message'])

    @run_on_executor
    def call_blocking(self):
        result = {
            'success': False,
            'data': {},
            'message': ''
        }
        data = self.json_args
        pwd = md5(data.get('password'))
        user_id = data.get('username')
        remember = data.get('remember')
        user = self.db_conn.query(User).options(joinedload(User.role, innerjoin=True))\
            .filter(User.userId == user_id)
        print(user)
        user = user.first()
        if user and user.password == pwd:
            if user.password == pwd:
                result['success'] = True
                result['data'] = user
                expires_days = None
                # remember = True
                if remember:
                    expires_days = 30
                json_user = jsonpickle.encode(user)
                self.set_secure_cookie('user', user_id, expires_days=expires_days)
                print(self.get_secure_cookie('user'))
            else:
                result['message'] = u'登录失败'
        else:
            result['message'] = u'登录失败'
        return result


class LogoutHandler(HandlerMixin, APIHandler):
    """
    登出
    """
    @unblock
    def get(self):
        """
        get方法
        :return:
        """
        self.clear_cookie('user')
        self.success(None)
